package com.hbmy.topic;

import java.io.IOException;
import java.util.Date;
import java.util.concurrent.TimeoutException;

import org.apache.commons.lang3.time.DateFormatUtils;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * 发送端routingKey必须明确
 * 
 * @author Administrator
 *
 */
public class EmitLogTopic
{
	private final static String EXCHANGE_NAME = "topic_logs";

	private static Connection connection;
	private static Channel channel;

	public static void main(String[] args)
	{
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost("localhost");
		factory.setPort(5682);

		String[] routingKeys = { "cron.err", "cron.inf", "cron.war", "kern.err", "kern.inf", "kern.war" };

		try
		{
			connection = factory.newConnection();
			channel = connection.createChannel();
			channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC);

			while (true)
			{
				Thread.sleep(1000);
				String message = "routing" + DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
				for (String routingKey : routingKeys)
				{
					channel.basicPublish(EXCHANGE_NAME, routingKey, null, message.getBytes("UTF-8"));
					System.out.println(" [x] Sent '" + routingKey + "':'" + message + "'");
				}
			}

		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TimeoutException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally
		{
			try
			{
				channel.close();
				connection.close();
			} catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (TimeoutException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
